import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author haomin
 * @date 2022/04/01 16:25
 **/
public class HeapSortTest {
    private static ThreadLocalRandom random = ThreadLocalRandom.current();
    public static void main(String[] args) {
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = random.nextInt(0,10);
        }
        long star = System.nanoTime();
        sort(arr);
        long end = System.nanoTime();
        System.out.println(Arrays.toString(arr));
        System.out.println("所用时间："+(end - star)/1000000 + "ms");
    }

    public static void sort(int[] arr){
        //堆化
        for (int i = (arr.length - 1 -1) >> 1 ; i >= 0 ; i--) {
            siftdown(arr,i,arr.length);
        }
        for (int i = arr.length - 1; i > 0 ; i--) {
            swap(arr,0,i);
            siftdown(arr,0,i);
        }
    }
    private static void siftdown(int[] arr, int i, int length) {
        while(((i << 1) + 1) < length){
            int j = (i << 1) + 1;
            if(j + 1 < length && arr[j] < arr[j+1]){
                j = j + 1;
            }

            if(arr[j] < arr[i]){
                break;
            }else {
                swap(arr,i,j);
                i = j;
            }
        }
    }
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}